import request from '@/utils/request'

export default {
  computed: {
    events() {
      if(!this.curComp) return {}
      const { list } = this.curComp.events
      const map = {}
      if(list && list.length) {
        list.forEach(item => {
          if(item.logicType == '0') { // 自定义逻辑
            const logic = item.logic
            const pars = item.params.split(',') // 形参
            const args = [...pars, logic]
            map[item.name] = new Function(...args).bind(this)
          } else if(item.logicType == '1') { // 页面跳转
            map[item.name] = this.eventToPage.bind(this, item.logicUrl, item.logicUrlParams)
          } else if(item.logicType == '2') { // 请求
            map[item.name] = this.eventSendRequest.bind(this, item.logicRequest)
          }
        })
      }
      return map
    }
  },
  methods: {
    // 事件页面跳转
    eventToPage(logicUrl, logicUrlParams) {
      logicUrlParams = logicUrlParams.filter(item => item.value) || []
      let param = ''
      if(logicUrlParams && logicUrlParams.length) {
        param = '?'
        let p = []
        logicUrlParams.forEach(item => {
          p.push(`${item.key}=${item.value}`)
        })
        param += p.join('&')
      }
      this.$router.push(`${logicUrl + param}`)
    },
    // 事件发送请求
    eventSendRequest(logicRequest) {
      if(logicRequest && logicRequest.length) {
        logicRequest.forEach(req => {
          const url = req.url
          const method = req.method
          const headers = this.getOptions(req.headers)
          const params = this.getOptions(req.params)
          const data = this.getOptions(req.body)
          request({ url, method, headers, params, data }).then(res => {
            const func = new Function('res', req.logic)
            func.call(this, res)
          })
        })
      }
    },
    getOptions(data) {
      const target = {}
      data.forEach(item => {
        try {
          target[item.key] = JSON.parse(item.value)
          if(typeof target[item.key] !== 'object') {
            target[item.key] = String(target[item.key])
          }
        }catch(e) {
          target[item.key] = item.value
        }
      })
      return target
    }
  }
}